package sky.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import sky.domain.*;
import sky.service.AirportService;
import sky.service.FlightService;
import sky.service.TicketService;
import sky.service.UserService;
import sky.tro.FlightLayer;
import sky.tro.TicketFinder;
import sky.tro.TicketParameters;
import sun.beans.editors.StringEditor;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 30.04.13
 * Time: 16:07
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class FlightController {

    @Autowired
    FlightService flightService;
    @Autowired
    TicketService ticketService;
    @Autowired
    UserService userService;
    @Autowired
    AirportService airportService;

    protected Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @ModelAttribute("showAuth")
    public Integer getAuth() {
        for (GrantedAuthority authority: getAuthentication().getAuthorities()) {
            if (authority.getAuthority().equals("ROLE_USER")) {
                return 1;
            }
            if (authority.getAuthority().equals("ROLE_ADMIN")) {
                return 2;
            }
        }
        return 0;
    }

    @RequestMapping(value = "/flights", method = RequestMethod.GET)
    public String mainFlights (@RequestParam("sort") String sortParam, Map<String, Object> map) {
        map.put("flightList", flightService.sortingList(sortParam));
        map.put("NFlight", new Flight());
        return "flights";
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yy HH:mm", Locale.ENGLISH);
        dateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
//        webDataBinder.registerCustomEditor(String.class, new DateToStringEditor());
    }

    @RequestMapping(value = "/addFlight", method = RequestMethod.POST)
    public String addFlight(@ModelAttribute("flight") Flight flight, BindingResult result) {
        flightService.addFlight(flight);
        ticketService.addTickets(flight);
        return "redirect:/flights?sort=id";
    }

    @RequestMapping(value = "/flights/delete/{flightId}", method = RequestMethod.GET)
    public String deleteFlight(@PathVariable("flightId") Integer flightId) {
        flightService.removeFlight(flightId);
        return "redirect:/flights?sort=id";
    }

    @RequestMapping(value = "/flights/edit/{flightId}", method = RequestMethod.GET)
    public String editFlight(@PathVariable("flightId") Integer flightId, Map<String, Object> map) {
        map.put("flight", flightService.getFlightById(flightId));
        return "editFlight";
    }

    @RequestMapping(value = "/flights/edit/*", method = RequestMethod.POST)
    public String editPlane(@ModelAttribute("flight") Flight flight, BindingResult result) {
        flightService.editFlight(flight);
        return "redirect:/flights?sort=id";
    }

    User getCurrentUser() {
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name;
        if (object instanceof UserDetails) {
            name = ((UserDetails) object).getUsername();
        }
        else {
            name = object.toString();
        }
        return userService.getUserByName(name);
    }

    @ModelAttribute("uzver")
    public User getUzver() {
        User user =  getCurrentUser();
        return user;
    }

    @ModelAttribute("SFlightList")
    public ArrayList<FlightLayer> sidebarShedule(@CookieValue(required = false, value = "currentAirport") String currentAirport) {
        if (currentAirport == null) currentAirport = "Minsk";
        Airport airport = airportService.getAirportByName(currentAirport);
        Date now = new Date();
        SimpleDateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
        ArrayList<FlightLayer> flightList = new ArrayList<FlightLayer>();
        for(Flight flight: airport.getFlightsIn()) {
            if (formatter1.format(now).equals(formatter1.format(flight.getDestinationDate()))) flightList.add(new FlightLayer(flight.getDestinationDate(),
                    "Arrive", flight.getDepartureAirport().getName()));
        }
        for(Flight flight: airport.getFlightsOut()) {
            if (formatter1.format(now).equals(formatter1.format(flight.getDepartureDate()))) flightList.add(new FlightLayer(flight.getDepartureDate(),
                    "Depart", flight.getDestinationAirport().getName()));
        }
        Collections.sort(flightList, new Comparator<FlightLayer>() {
            public int compare(FlightLayer o1, FlightLayer o2) {
                return o1.getDate().compareTo(o2.getDate());
            }
        });
        return flightList;
    }

    @ModelAttribute("currentAirport")
    public String currentAirport(@CookieValue(required = false, value = "currentAirport") String currentAirport) {
        if (currentAirport == null) currentAirport = "Minsk";
        return currentAirport;
    }


    @ModelAttribute("userFlightList")
    public ArrayList<Flight> shedule() {
        User user = getCurrentUser();
        ArrayList <Flight> flightList = new ArrayList<Flight>();
        if (user != null) {
            Date now = new Date();
            SimpleDateFormat formatter1 = new SimpleDateFormat("dd.MM.yyyy");
            for (Ticket ticket: user.getTickets()) {
                flightList.add(ticket.getFlight());
            }
            Collections.sort(flightList, new Comparator<Flight>() {
                public int compare(Flight o1, Flight o2) {
                    return o1.getDepartureDate().compareTo(o2.getDepartureDate());
                }
            });
        }
        return flightList;
    }
}
